export class MainStore {
  constructor() {
    this.progressBarDom = null
    this.progressPerscent = 0
    this.pixelStreamSrc = ''
    this.senceId = ''
  }

  setProgressPerscent(pecent) {
    this.progressPerscent = pecent
    this.setAnimateProgress()
  }

  setSenceId(val) {
    this.senceId = val
  }

  setPixelStreamSrc(url = null) {
    if (!url) {
      this.pixelStreamSrc = ''
    }
    this.pixelStreamSrc = url
  }

  initProgressBarDom(id) {
    this.progressBarDom = document.getElementById(id)?.children[0]
    if (!this.progressBarDom) {
      console.error('Progress bar DOM not found.')
    }
  }

  setProgressBarDomDisplay(display) {
    if (!this.progressBarDom) {
      console.error('Progress bar DOM is not initialized.')
      return
    }
    const parent = this.progressBarDom.parentNode
    if (parent) {
      parent.style.visibility = display ? 'visible' : 'hidden'
    } else {
      console.error('Progress bar DOM does not have a parent node.')
    }
  }

  setAnimateProgress() {
    const _this = this
    const element = this.progressBarDom.querySelector('.ui-progress')
    element.style.display = 'block'
    const duration = 2000
    const easing = 'swing'
    let start = null
    const initialWidth = parseInt(element.style.width, 10) || 0
    const step = (timestamp) => {
      if (!start) start = timestamp
      const progressTime = timestamp - start
      const progressPercent = Math.min(progressTime / duration, 1)
      let easeProgress = progressPercent
      if (easing === 'swing') {
        easeProgress = 0.5 - Math.cos(progressPercent * Math.PI) / 2
      }
      const currentWidth = initialWidth + (_this.progressPerscent - initialWidth) * easeProgress
      element.style.width = currentWidth + '%'
      const labelEl = element.querySelector('.ui-label')
      const valueEl = labelEl.querySelector('.value')
      if (Math.ceil(currentWidth) < 20 && labelEl.style.display !== 'none') {
        labelEl.style.display = 'none'
      } else {
        if (labelEl.style.display === 'none') {
          labelEl.style.display = 'block'
        }
      }
      if (Math.ceil(currentWidth) <= 100) {
        valueEl.textContent = Math.ceil(currentWidth) + '%'
      }
      if (progressTime < duration) {
        window.requestAnimationFrame(step)
      }
    }
    window.requestAnimationFrame(step)
  }
}

const mainStoreInstance = new MainStore()
export default mainStoreInstance
